<?php

namespace app\admin\controller;

use app\admin\validate\AdvItemValidate;
use app\admin\validate\ArticleFieldsValidate;
use app\admin\validate\ArticleValidate;
use app\admin\validate\AttachmentsValidate;
use app\admin\validate\CategoryValidate;
use app\admin\validate\ImagesValidate;
use app\common\facade\CategoryFacade;
use app\common\model\AdvGroupModel;
use app\common\model\AdvItemModel;
use app\common\model\ArticleCommentModel;
use app\common\model\ArticleFieldsModel;
use app\common\model\ArticleModel;
use app\common\model\CategoryModel;
use app\common\model\UrlModel;
use Overtrue\Pinyin\Pinyin;
use think\Db;
use think\Exception;
use think\facade\Log;
use think\response\Json;

class ChannelController extends BaseController
{
    protected $channel;
    protected $cates;

    protected function initChannel($channel_id)
    {
        $this->channel = CategoryFacade::findCategory($channel_id);
        if (empty($this->channel)) {
            $this->error('频道错误');
        }
        $allcates = CategoryFacade::getCategories();
        $this->cates = getSortedCategory($allcates, $channel_id);

        $this->channel['fields'] = force_json_decode($this->channel['fields']);
        if (!$this->request->isAjax()) {
            $this->assign('channel_id', $channel_id);
            $this->assign('channel', $this->channel);
            $this->assign('category', $this->cates);
        }
    }

    /**
     * 初始化频道
     * @param string $act 
     * @param int $id 
     * @return string 
     */
    public function init($act = '', $id = 0)
    {
        if ($act == 'delete') {
            $this->deleteChannel(intval($id));
        }
        if ($this->request->isPost()) {
            $channels = $this->request->post('channels');
            $lastid = 0;
            foreach ($channels as $cid => $data) {
                if (empty($data['title']) || empty($data['name'])) continue;

                // name不能重复
                $exists = Db::name('category')->where('id', '<>', intval($cid))->where('name', $data['name'])->find();
                if (!empty($exists)) {
                    continue;
                }
                $data['pid'] = 0;
                if (is_numeric($cid)) {
                    Db::name('Category')->where('id', $cid)->update($data);
                    $lastid = $cid;
                } else {
                    $insertid = Db::name('Category')->insert($data, false, true);
                }
                if ($lastid <= 0) {
                    $lastid = $insertid;
                }
            }
            CategoryFacade::clearCache();
            getMenus(true);

            $channels = CategoryFacade::getSubCategory(0);
            writeConstants('channels', implode('|', array_column($channels, 'name')));
            $this->success('保存成功！', url('channel/index', ['channel_id' => $lastid]));
        }

        $channels = CategoryFacade::getSubCategory(0);
        if (empty($channels)) {
            $channels = [
                ['id' => 'a1', 'title' => '产品中心', 'short' => '产品', 'name' => 'goods', 'channel_mode' => 0, 'use_template' => 1, 'is_images' => 1],
                ['id' => 'a2', 'title' => '案例展示', 'short' => '案例', 'name' => 'cases', 'channel_mode' => 0, 'use_template' => 1, 'is_images' => 1],
                ['id' => 'a3', 'title' => '新闻中心', 'short' => '新闻', 'name' => 'news', 'channel_mode' => 0, 'use_template' => 0, 'is_images' => 0],
                ['id' => 'a4', 'title' => '关于我们', 'short' => '关于', 'name' => 'about', 'channel_mode' => 1, 'use_template' => 1, 'is_images' => 0]
            ];
        }
        $this->assign('channels', $channels);
        return $this->fetch();
    }

    /**
     * 删除栏目
     * @param mixed $id 
     * @return void 
     */
    private function deleteChannel($id)
    {
        $exists = CategoryFacade::findCategory($id);
        if (empty($exists) || $exists['pid'] != 0) {
            $this->error("频道不存在");
        }
        //查询属于这个分类的文章
        $posts = Db::name('Article')->where('channel_id', $id)->select();
        if (!empty($posts)) {
            Db::name('Article')->where('channel_id', $id)->delete();
            Db::name('ArticleComment')->where('channel_id', $id)->delete();
            $artids = array_column($posts, 'id');
            Db::name('ArticleImages')->whereIn('article_id', $artids)->delete();
            Db::name('ArticleDigg')->whereIn('article_id', $artids)->delete();
        }
        //删除栏目和所有子分类
        $childIds = CategoryFacade::getSubCateIds($id, true, true);
        if (!empty($childIds)) {
            Db::name('Category')->whereIn('id', $childIds)->delete();
        }

        CategoryFacade::clearCache();
        user_log($this->mid, 'deletechannel', 1, '删除栏目 ' . $id . ' ' . $exists['title'], 'manager');
        $this->success('删除成功');
    }

    /**
     * 频道内容列表
     * @param int $channel_id 
     * @param string $keyword 
     * @param int $cate_id 
     * @return string 
     */
    public function index($channel_id, $keyword = '', $cate_id = 0)
    {
        if ($this->request->isPost()) {
            return redirect(url('', ['channel_id' => $channel_id, 'cate_id' => $cate_id, 'keyword' => base64url_encode($keyword)]));
        }
        $keyword = empty($keyword) ? '' : base64url_decode($keyword);
        $this->initChannel($channel_id);

        $model = Db::view('article', '*')
            ->view('category', ['name' => 'category_name', 'title' => 'category_title'], 'article.cate_id=category.id', 'LEFT')
            ->view('manager', ['username'], 'article.user_id=manager.id', 'LEFT')
            ->where('channel_id', $channel_id);
        if (!empty($keyword)) {
            $model->whereLike('article.title|manager.username|category.title', "%$keyword%");
        }
        if ($cate_id > 0) {
            $model->whereIn('article.cate_id', CategoryFacade::getSubCateIds($cate_id));
        }

        $orderstr = 'article.id desc';
        if (!empty($this->channel['list_sort'])) {
            $orderstr = 'article.' . $this->channel['list_sort'] . ',' . $orderstr;
        }
        $orderstr = '(article.type & 2) desc,' . $orderstr;

        $lists = $model->order(Db::raw($orderstr))->paginate(15);
        $cateCounts = $model->setOption('field', ['count(article.id) as article_count, cate_id'])->setOption('order', 'cate_id')->group('cate_id')->select();

        $this->assign('fields', ArticleFieldsModel::getFields(true));
        $this->assign('lists', $lists);
        $this->assign('page', $lists->render());
        $this->assign('cate_id', $cate_id);
        $this->assign('keyword', $keyword);
        $this->assign('counts', $cateCounts);
        $this->assign('types', getArticleTypes());
        return $this->fetch();
    }

    /**
     * 设置url
     * @return void 
     */
    public function setUrl()
    {
        $fullUrl = $this->request->post('fullurl');
        $shortUrl = $this->request->post('shorturl');
        $shortUrl = '/' . ltrim($shortUrl, '/');
        if (preg_match('/^\/(admin|api|index|task|vue)/', $shortUrl)) {
            $this->error('url不能以 admin,api,index,task,vue 开头');
        }
        if (empty($shortUrl)) {
            UrlModel::where('full', $fullUrl)->delete();
        } else {
            UrlModel::create(['short' => $shortUrl, 'full' => $fullUrl], null, true);
        }
        UrlModel::clearCacheData();
        $this->success('配置成功');
    }

    /**
     * 频道配置
     * @param int $channel_id 
     * @return string 
     */
    public function setting($channel_id)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new CategoryValidate();
            $validate->setId($channel_id);

            if (!$validate->check($data)) {
                $this->error($validate->getError());
            } else {
                if (in_array($data['name'], ['admin', 'api', 'index', 'vue', 'task', 'user', 'order', 'channel', 'cart', 'share', 'auth', 'article'])) {
                    $this->error('频道名不合法');
                }
                $delete_images = [];
                $iconupload = $this->_upload('category', 'upload_icon');
                if (!empty($iconupload)) {
                    $data['icon'] = $iconupload['url'];
                    $delete_images[] = $data['delete_icon'];
                }
                $uploaded = $this->_upload('category', 'upload_image');
                if (!empty($uploaded)) {
                    $data['image'] = $uploaded['url'];
                    $delete_images[] = $data['delete_image'];
                }
                unset($data['delete_icon']);
                unset($data['delete_image']);

                try {
                    $result = CategoryModel::update($data, ['id' => $channel_id]);
                    if ($result) {
                        delete_image($delete_images);
                        if ($data['is_top']) {
                            CategoryModel::where('id', '<>', $channel_id)->update(['is_top' => 0]);
                        }

                        CategoryFacade::clearCache();
                    }
                } catch (\Exception $e) {
                    throw $e;
                    Log::error($e->getMessage());
                    delete_image([$data['icon'], $data['image']]);
                    $this->error(lang('Update failed!'));
                }
                $channels = CategoryFacade::getSubCategory(0);
                writeConstants('channels', implode('|', array_column($channels, 'name')));
                user_log($this->mid, 'settingchannel', 1, '设置栏目 ' . $channel_id . ' ' . $this->channel['title'], 'manager');
                $this->success(lang('Update success!'), url('channel/setting', ['channel_id' => $channel_id]));
            }
        }
        $this->initChannel($channel_id);
        $this->assign('fields', ArticleFieldsModel::getFields());
        return $this->fetch();
    }

    /**
     * banner 列表
     * @param int $channel_id 
     * @return string 
     */
    public function banner($channel_id)
    {
        $this->initChannel($channel_id);
        $group = Db::name('AdvGroup')->where('flag', 'channel_' . $channel_id)->find();
        if (empty($group)) {
            $gid = Db::name('AdvGroup')->insert([
                'title' => $this->channel['title'],
                'flag' => 'channel_' . $channel_id,
                'width' => '1920',
                'height' => '',
                'ext_set' => '',
                'locked' => 1,
                'status' => 1,
                'create_time' => time(),
                'update_time' => time()
            ], false, true);
        } else {
            $gid = $group['id'];
        }
        $banners = Db::name('AdvItem')->where('group_id', $gid)->paginate(15);

        $this->assign('gid', $gid);
        $this->assign('lists', $banners);
        return $this->fetch();
    }

    /**
     * 添加banner
     * @param $channel_id
     * @param $gid
     * @return string
     */
    public function banneradd($channel_id, $gid)
    {
        $gid = intval($gid);
        $channel_id = intval($channel_id);
        $group = AdvGroupModel::get($gid);
        if (empty($group)) {
            $this->error('广告组不存在');
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new AdvItemValidate();

            if (!$validate->check($data)) {
                $this->error($validate->getError());
            } else {
                $uploaded = $this->_upload('banner', 'upload_image');
                if (!empty($uploaded)) {
                    $data['image'] = $uploaded['url'];
                } elseif ($this->uploadErrorCode > 102) {
                    $this->error($this->uploadErrorCode . ':' . $this->uploadError);
                }
                $uploaded = $this->_uploadFile('banner', 'upload_video', 2);
                if (!empty($uploaded)) {
                    $data['video'] = $uploaded['url'];
                } elseif ($this->uploadErrorCode > 102) {
                    $this->error($this->uploadErrorCode . ':' . $this->uploadError);
                }

                $url = url('channel/banner', array('channel_id' => $channel_id));
                $data['start_date'] = empty($data['start_date']) ? 0 : strtotime($data['start_date']);
                $data['end_date'] = empty($data['end_date']) ? 0 : strtotime($data['end_date']);
                if (isset($data['ext'])) {
                    $data['ext_data'] = $data['ext'];
                    unset($data['ext']);
                }
                if (isset($data['elements'])) {
                    $data['elements'] = $this->filterElements($data['elements']);
                }
                $model = AdvItemModel::create($data);
                if ($model['id']) {
                    $this->success(lang('Add success!'), $url);
                } else {
                    delete_image($data['image']);
                    $this->error(lang('Add failed!'));
                }
            }
        }
        $this->initChannel($channel_id);
        $model = array('status' => 1, 'group_id' => $gid, 'ext' => []);
        $this->assign('group', $group);
        $this->assign('model', $model);
        $this->assign('id', 0);
        return $this->fetch('bannerupdate');
    }

    /**
     * 修改banner
     * @param int $channel_id
     * @param int $id
     * @return string
     */
    public function bannerupdate($channel_id, $id)
    {
        $id = intval($id);
        $model = Db::name('AdvItem')->where('id', $id)->find();
        if (empty($model)) {
            $this->error('广告项不存在');
        }
        $model = AdvGroupModel::fixAdItem($model);
        $group = AdvGroupModel::get($model['group_id']);
        if (empty($group)) {
            $this->error('广告组不存在');
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new AdvItemValidate();

            if (!$validate->check($data)) {
                $this->error($validate->getError());
            } else {
                $model = AdvItemModel::where('id', $id)->find();
                $url = url('channel/banner', array('channel_id' => $channel_id));
                $delete_images = [];
                $uploaded = $this->_upload('banner', 'upload_image');
                if (!empty($uploaded)) {
                    $data['image'] = $uploaded['url'];
                    $delete_images[] = $data['delete_image'];
                } elseif ($this->uploadErrorCode > 102) {
                    $this->error($this->uploadErrorCode . ':' . $this->uploadError);
                }
                unset($data['delete_image']);

                $uploaded = $this->_uploadFile('banner', 'upload_video', 2);
                if (!empty($uploaded)) {
                    $data['video'] = $uploaded['url'];
                } elseif ($this->uploadErrorCode > 102) {
                    $this->error($this->uploadErrorCode . ':' . $this->uploadError);
                }

                $data['start_date'] = empty($data['start_date']) ? 0 : strtotime($data['start_date']);
                $data['end_date'] = empty($data['end_date']) ? 0 : strtotime($data['end_date']);
                if (isset($data['ext'])) {
                    $data['ext_data'] = $data['ext'];
                    unset($data['ext']);
                }
                if (isset($data['elements'])) {
                    $data['elements'] = $this->filterElements($data['elements']);
                }

                if ($model->allowField(true)->save($data)) {
                    delete_image($delete_images);
                    $this->success(lang('Update success!'), $url);
                } else {
                    delete_image($data['image']);
                    $this->error(lang('Update failed!'));
                }
            }
        }
        $this->initChannel($channel_id);
        $this->assign('group', $group);
        $this->assign('model', $model);
        $this->assign('id', $id);
        return $this->fetch();
    }

    private function filterElements($elements)
    {
        $fields = [];
        foreach ($elements as $k => $item) {
            if ($item['type'] == 'image') {
                $fields[] = "elements_{$k}_image";
            }
        }

        $uploaded = $this->_batchUpload('banner', $fields);
        if (!empty($uploaded)) {
            foreach ($uploaded as $k => $file) {
                $newkey = explode('_', $k . '_');
                $newkey = $newkey[1];
                $elements[$newkey]['image'] = $file;
            }
        } elseif ($this->uploadErrorCode > 102) {
            $this->error($this->uploadErrorCode . ':' . $this->uploadError);
        }
        return array_values($elements);
    }

    /**
     * 删除banner
     * @param int $id 
     * @return void 
     */
    public function bannerdelete($id)
    {
        $id = intval($id);
        $result = AdvItemModel::where('id', $id)->delete();
        if ($result) {
            $this->success(lang('Delete success!'));
        } else {
            $this->error(lang('Delete failed!'));
        }
    }

    /**
     * 获取/添加/编辑分类
     * @param int $channel_id 
     * @param int $id 
     * @return Json 
     */
    public function category($channel_id, $id = 0)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new CategoryValidate();
            $validate->setId($id);

            if (!$validate->check($data)) {
                $this->error($validate->getError());
            } else {
                $delete_images = [];
                $iconupload = $this->_upload('category', 'upload_icon');
                if (!empty($iconupload)) {
                    $data['icon'] = $iconupload['url'];
                    $delete_images[] = $data['delete_icon'];
                }
                $uploaded = $this->_upload('category', 'upload_image');
                if (!empty($uploaded)) {
                    $data['image'] = $uploaded['url'];
                    $delete_images[] = $data['delete_image'];
                }
                unset($data['delete_icon']);
                unset($data['delete_image']);
                if (empty($data['pid'])) {
                    $data['pid'] = $channel_id;
                }

                try {
                    if ($id > 0) {
                        $result = CategoryModel::update($data, ['id' => $id]);
                    } else {
                        $result = CategoryModel::create($data);
                    }
                    if ($result) {
                        delete_image($delete_images);
                        CategoryFacade::clearCache();
                    }
                } catch (\Exception $e) {
                    throw $e;
                    Log::error($e->getMessage());
                    delete_image([$data['icon'], $data['image']]);
                    $this->error($id > 0 ? lang('Update failed!') : lang('Add failed!'));
                }
                $this->success($id > 0 ? lang('Update success!') : lang('Add success!'));
            }
        }
        $cate = CategoryModel::where('id', $id)->find();
        return json(['cate' => $cate, 'code' => 1]);
    }


    /**
     * 批量添加分类
     * @param int $channel_id 
     * @param int $pid 
     * @return void 
     */
    public function category_batch($channel_id, $pid = 0)
    {
        $content = $this->request->post('content');
        $rows = explode("\n", $content);
        $datas = [];
        $names = Db::name('category')->field('name')->select();
        $names = array_column($names, 'name');
        $pinyin = new Pinyin();
        $sort = 0;
        if ($pid > 0) {
            $sort = Db::name('category')->where('pid', $pid)->max('sort') + 1;
        } else {
            $sort = Db::name('category')->max('sort') + 1;
        }
        foreach ($rows as $item) {
            $item = trim($item);
            if (empty($item)) continue;
            $fields = explode(' ', $item);
            $fieldCount = count($fields);
            $data = ['pid' => $pid, 'sort' => $sort++];
            if ($fieldCount > 2) {
                $data['title'] = trim($fields[0]);
                $data['short'] = trim($fields[1]);
                $data['name'] = trim($fields[2]);
            } elseif ($fieldCount > 1) {
                $data['title'] = trim($fields[0]);
                $data['short'] = trim($fields[0]);
                $data['name'] = trim($fields[1]);
            } else {
                $data['title'] = trim($fields[0]);
                $data['short'] = trim($fields[0]);
                $data['name'] = $pinyin->permalink(trim($fields[0]), '');
            }
            if (in_array($data['name'], $names)) {
                $parts = explode('_', $data['name']);
                $partCount = count($parts);
                if (count($parts) > 1) {
                    $parts[$partCount - 1] += 1;
                    while (((in_array(implode('_', $parts), $names)))) {
                        $parts[$partCount - 1] += 1;
                    }
                } else {
                    $parts[] = 1;
                    while (((in_array(implode('_', $parts), $names)))) {
                        $parts[$partCount] += 1;
                    }
                }
                $data['name'] = implode('_', $parts);
            }
            $names[] = $data['name'];

            $datas[] = $data;
            unset($data);
        }
        if (!empty($datas)) {
            Db::name('category')->insertAll($datas);
            CategoryFacade::clearCache();
            $this->success('添加成功');
        }
        $this->error('未提交数据');
    }

    /**
     * 删除分类
     * @param mixed $id 
     * @return void 
     */
    public function category_delete($id)
    {
        $id = intval($id);
        $model = Db::name('Category')->where('id', $id)->find();
        if (empty($model)) {
            $this->error('分类不存在');
        }
        $hasson = Db::name('Category')->where('pid', $id)->count();
        if ($hasson > 0) {
            $this->error('请先删除子类');
        }
        Db::name('Category')->where('id', $id)->delete();
        Db::name('article')->where('cate_id', $id)->update(['cate_id' => 0]);
        CategoryFacade::clearCache();
        $this->success('删除成功！');
    }

    /**
     * 添加
     * @param int $channel_id
     * @param int $cid
     * @return mixed
     */
    public function add($channel_id, $cid = 0)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new ArticleValidate();
            $validate->setId(0);

            if (!$validate->check($data)) {
                $this->error($validate->getError());
            } else {
                $delete_images = [];
                $uploaded = $this->_upload('article', 'upload_cover');
                if (!empty($uploaded)) {
                    $data['cover'] = $uploaded['url'];
                    $delete_images[] = $data['delete_cover'];
                } elseif ($this->uploadErrorCode > 102) {
                    $this->error($this->uploadErrorCode . ':' . $this->uploadError);
                }
                unset($data['delete_cover']);
                $data['user_id'] = $this->mid;
                if (!empty($data['prop_data'])) {
                    $data['prop_data'] = array_combine($data['prop_data']['keys'], $data['prop_data']['values']);
                } else {
                    $data['prop_data'] = [];
                }
                if (empty($data['description'])) $data['description'] = cutstr($data['content'], 240);
                if (!empty($data['create_time'])) $data['create_time'] = strtotime($data['create_time']);
                if (empty($data['create_time'])) unset($data['create_time']);
                if ($this->channel['mode'] == 1) {
                    $data['is_hidden'] = 1;
                }

                $model = ArticleModel::create($data);
                if ($model->id) {
                    delete_image($delete_images);
                    user_log($this->mid, 'addarticle', 1, '添加文章 ' . $model->id, 'manager');
                    $this->success(lang('Add success!'), url('channel/index', ['channel_id' => $channel_id]));
                } else {
                    delete_image($data['cover']);
                    $this->error(lang('Add failed!'));
                }
            }
        }
        $this->initChannel($channel_id);
        $model = array('type' => 1, 'cate_id' => $cid, 'digg' => 0, 'views' => 0);
        $fields = ArticleFieldsModel::getSelectedFields($this->channel['fields']);
        foreach ($fields as $field) {
            $model[$field['name']] = $field['data_value'];
        }
        $this->assign('article', $model);
        $this->assign('fields', $fields);
        $this->assign('types', getArticleTypes());
        $this->assign('copyrights', Db::name('copyrights')->order('sort asc')->select());
        $this->assign('id', 0);
        return $this->fetch('edit');
    }

    /**
     * 修改
     * @param int $channel_id
     * @param int $id
     * @return mixed
     */
    public function edit($channel_id, $id)
    {
        $id = intval($id);

        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new ArticleValidate();
            $validate->setId($id);

            if (!$validate->check($data)) {
                $this->error($validate->getError());
            } else {
                $delete_images = [];
                $uploaded = $this->_upload('article', 'upload_cover');
                if (!empty($uploaded)) {
                    $data['cover'] = $uploaded['url'];
                    $delete_images[] = $data['delete_cover'];
                } elseif ($this->uploadErrorCode > 102) {
                    $this->error($this->uploadErrorCode . ':' . $this->uploadError);
                }
                if (!empty($data['prop_data'])) {
                    $data['prop_data'] = array_combine($data['prop_data']['keys'], $data['prop_data']['values']);
                } else {
                    $data['prop_data'] = [];
                }
                if (empty($data['description'])) $data['description'] = cutstr($data['content'], 240);
                if (!empty($data['create_time'])) $data['create_time'] = strtotime($data['create_time']);
                if (empty($data['create_time'])) unset($data['create_time']);
                $model = ArticleModel::get($id);
                try {
                    $model->allowField(true)->save($data);
                    delete_image($delete_images);
                    user_log($this->mid, 'updatearticle', 1, '修改文章 ' . $id, 'manager');
                } catch (\Exception $err) {
                    delete_image($data['cover']);
                    $this->error(lang('Update failed: %', [$err->getMessage()]));
                }
                $this->success(lang('Update success!'), url('channel/index', ['channel_id' => $channel_id]));
            }
        }
        $this->initChannel($channel_id);
        $model = ArticleModel::get($id);
        if (empty($model)) {
            $this->error('文章不存在');
        }

        $this->assign('article', ArticleFieldsModel::readTransData($model));
        $this->assign('fields', ArticleFieldsModel::getSelectedFields($this->channel['fields']));
        $this->assign('types', getArticleTypes());
        $this->assign('copyrights', Db::name('copyrights')->order('sort asc')->select());
        $this->assign('id', $id);
        return $this->fetch();
    }

    /**
     * 批量添加内容
     * @param int $channel_id
     * @param int $cid
     * @return string 
     */
    public function batch($channel_id, $cid = 0)
    {
        $cid = intval($cid);

        if ($this->request->isPost()) {
        }
        $this->initChannel($channel_id);
        if (empty($cid)) {
            $cid = $this->channel['id'];
        }
        $this->assign('cate_id', $cid);
        $this->assign('fields', ArticleFieldsModel::getSelectedFields($this->channel['fields']));
        return $this->fetch();
    }

    /**
     * 删除文章
     * @param $id
     */
    public function delete($id)
    {
        $model = Db::name('article');
        $result = $model->whereIn("id", idArr($id))->delete();
        if ($result) {
            Db::name('articleComment')->whereIn("article_id", idArr($id))->delete();
            Db::name('articleDigg')->whereIn("article_id", idArr($id))->delete();
            Db::name('articleImages')->whereIn("article_id", idArr($id))->delete();
            user_log($this->mid, 'deletearticle', 1, '删除文章 ' . $id, 'manager');
            $this->success(lang('Delete success!'));
        } else {
            $this->error(lang('Delete failed!'));
        }
    }

    /**
     * 发布
     * @param $id
     * @param int $status
     */
    public function status($id, $status = 0)
    {
        $data['status'] = $status == 1 ? 1 : 0;

        $result = Db::name('article')->whereIn("id", idArr($id))->update($data);
        if ($result && $data['status'] === 1) {
            user_log($this->mid, 'pusharticle', 1, '发布文章 ' . $id, 'manager');
            $this->success("发布成功");
        } elseif ($result && $data['status'] === 0) {
            user_log($this->mid, 'cancelarticle', 1, '撤销文章 ' . $id, 'manager');
            $this->success("撤销成功");
        } else {
            $this->error("操作失败");
        }
    }

    public function fields()
    {
        $fields = Db::name('articleFields')->order('sort ASC, id ASC')->select();

        $this->assign('lists', $fields);
        return $this->fetch();
    }

    public function fieldsadd()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new ArticleFieldsValidate();
            $validate->setId(0);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            try {
                ArticleFieldsModel::create($data);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('添加成功');
        }
        return $this->fetch('fieldsedit');
    }
    public function fieldsedit($id)
    {
        $id = intval($id);
        $field = ArticleFieldsModel::where('id', $id)->find();
        if (empty($field)) {
            $this->error('字段不存在');
        }
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new ArticleFieldsValidate();
            $validate->setId($id);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            try {
                $field->allowField(true)->save($data);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('保存成功');
        }

        if (!empty($field['data_options'])) {
            $field['data_options'] = array_combine($field['data_options']['keys'], $field['data_options']['values']);
        }
        $this->assign('model', $field);
        return $this->fetch();
    }

    /**
     * 图集
     * @param $aid
     * @param $key
     * @return mixed
     * @throws Exception
     */
    public function imagelist($channel_id, $aid, $key = '')
    {
        $this->initChannel($channel_id);
        $model = Db::name('ArticleImages');
        $article = Db::name('Article')->find($aid);
        if (empty($article)) {
            $this->error('文章不存在');
        }
        $model->where('article_id', $aid);
        if (!empty($key)) {
            $model->where('title', 'like', "%$key%");
        }
        $lists = $model->order('sort ASC,id DESC')->paginate(15);
        $this->assign('article', $article);
        $this->assign('lists', $lists);
        $this->assign('page', $lists->render());
        $this->assign('aid', $aid);
        return $this->fetch();
    }

    /**
     * 添加图片
     * @param $aid
     * @return mixed
     */
    public function imageadd($channel_id, $aid)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['article_id'] = $aid;
            $validate = new ImagesValidate();

            if (!$validate->check($data)) {
                $this->error($validate->getError());
            } else {
                $uploaded = $this->_upload('images', 'upload_image');
                if (!empty($uploaded)) {
                    $data['image'] = $uploaded['url'];
                } else {
                    $this->error($this->uploadError);
                }
                $data['create_time'] = time();
                $data['update_time'] = time();
                $model = Db::name("ArticleImages");
                $url = url('channel/imagelist', array('channel_id' => $channel_id, 'aid' => $aid));
                if ($model->insert($data)) {
                    $this->success(lang('Add success!'), $url);
                } else {
                    delete_image($data['image']);
                    $this->error(lang('Add failed!'));
                }
            }
        }
        $this->initChannel($channel_id);
        $model = array('status' => 1, 'article_id' => $aid);
        $this->assign('model', $model);
        $this->assign('aid', $aid);
        $this->assign('id', 0);
        return $this->fetch('imageupdate');
    }

    /**
     * 修改图片
     * @param $id
     * @return mixed
     */
    public function imageupdate($channel_id, $id)
    {
        $id = intval($id);

        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new ImagesValidate();

            if (!$validate->check($data)) {
                $this->error($validate->getError());
            } else {
                $model = Db::name("ArticleImages");
                $url = url('channel/imagelist', array('channel_id' => $channel_id, 'aid' => $data['article_id']));
                $delete_images = [];
                $uploaded = $this->_upload('images', 'upload_image');
                if (!empty($uploaded)) {
                    $data['image'] = $uploaded['url'];
                    $delete_images[] = $data['delete_image'];
                } elseif (!$this->_noFile()) {
                    $this->error($this->uploadErrorCode . ':' . $this->uploadError);
                }
                unset($data['delete_image']);
                $data['id'] = $id;
                $data['update_time'] = time();
                if ($model->update($data)) {
                    delete_image($delete_images);
                    $this->success(lang('Update success!'), $url);
                } else {
                    delete_image($data['image']);
                    $this->error(lang('Update failed!'));
                }
            }
        }
        $this->initChannel($channel_id);
        $model = Db::name('ArticleImages')->where('id', $id)->find();
        if (empty($model)) {
            $this->error('图片不存在');
        }

        $this->assign('model', $model);
        $this->assign('aid', $model['article_id']);
        $this->assign('id', $id);
        return $this->fetch();
    }

    /**
     * 删除图片
     * @param $aid
     * @param $id
     */
    public function imagedelete($aid, $id)
    {
        $id = intval($id);
        $model = Db::name('ArticleImages')->where('id', $id)->find();
        if (empty($model)) {
            $this->error('图片不存在');
        }
        $result = Db::name('ArticleImages')->where('id', $id)->delete();
        if ($result) {
            delete_image($model['image']);
            $this->success(lang('Delete success!'));
        } else {
            $this->error(lang('Delete failed!'));
        }
    }

    /**
     * 附件
     * @param $aid
     * @param $key
     * @return mixed
     * @throws Exception
     */
    public function attachmentlist($channel_id, $aid, $key = '')
    {
        $this->initChannel($channel_id);
        $model = Db::name('ArticleAttachments');
        $article = Db::name('Article')->find($aid);
        if (empty($article)) {
            $this->error('文章不存在');
        }
        $model->where('article_id', $aid);
        if (!empty($key)) {
            $model->where('title', 'like', "%$key%");
        }
        $lists = $model->order('sort ASC,id DESC')->paginate(15);
        $this->assign('article', $article);
        $this->assign('lists', $lists);
        $this->assign('page', $lists->render());
        $this->assign('aid', $aid);
        return $this->fetch();
    }

    /**
     * 添加附件
     * @param $aid
     * @return mixed
     */
    public function attachmentadd($channel_id, $aid)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['article_id'] = $aid;
            $validate = new AttachmentsValidate();

            if (!$validate->check($data)) {
                $this->error($validate->getError());
            } else {
                $uploaded = $this->_uploadFile('attachs', 'upload_attachment');
                if (!empty($uploaded)) {
                    $data['url'] = $uploaded['url'];
                } else {
                    $this->error($this->uploadError);
                }
                $data['create_time'] = time();
                $data['update_time'] = time();
                $model = Db::name("ArticleAttachments");
                $url = url('channel/attachmentlist', array('channel_id' => $channel_id, 'aid' => $aid));
                if ($model->insert($data)) {
                    $this->success(lang('Add success!'), $url);
                } else {
                    delete_image($data['url']);
                    $this->error(lang('Add failed!'));
                }
            }
        }
        $this->initChannel($channel_id);
        $model = array('status' => 1, 'article_id' => $aid);
        $this->assign('model', $model);
        $this->assign('aid', $aid);
        $this->assign('id', 0);
        return $this->fetch('attachmentupdate');
    }

    /**
     * 修改附件
     * @param $id
     * @return mixed
     */
    public function attachmentupdate($channel_id, $id)
    {
        $id = intval($id);

        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new AttachmentsValidate();

            if (!$validate->check($data)) {
                $this->error($validate->getError());
            } else {
                $model = Db::name("ArticleAttachments");
                $url = url('channel/attachmentlist', array('channel_id' => $channel_id, 'aid' => $data['article_id']));
                $delete_files = [];
                $uploaded = $this->_uploadFile('attachs', 'upload_attachment');
                if (!empty($uploaded)) {
                    $data['url'] = $uploaded['url'];
                    $delete_files[] = $data['delete_attachment'];
                } elseif (!$this->_noFile()) {
                    $this->error($this->uploadErrorCode . ':' . $this->uploadError);
                }
                unset($data['delete_attachment']);
                $data['id'] = $id;
                $data['update_time'] = time();
                if ($model->update($data)) {
                    delete_image($delete_files);
                    $this->success(lang('Update success!'), $url);
                } else {
                    delete_image($data['url']);
                    $this->error(lang('Update failed!'));
                }
            }
        }
        $this->initChannel($channel_id);
        $model = Db::name('ArticleAttachments')->where('id', $id)->find();
        if (empty($model)) {
            $this->error('附件不存在');
        }

        $this->assign('model', $model);
        $this->assign('aid', $model['article_id']);
        $this->assign('id', $id);
        return $this->fetch();
    }

    /**
     * 删除图片
     * @param $aid
     * @param $id
     */
    public function attachmentdelete($aid, $id)
    {
        $id = intval($id);
        $model = Db::name('ArticleAttachments')->where('id', $id)->find();
        if (empty($model)) {
            $this->error('图片不存在');
        }
        $result = Db::name('ArticleAttachments')->where('id', $id)->delete();
        if ($result) {
            delete_image($model['url']);
            $this->success(lang('Delete success!'));
        } else {
            $this->error(lang('Delete failed!'));
        }
    }


    /**
     * 评论管理
     * @param int $id
     * @param int $category
     * @param string $key
     * @return mixed
     */
    public function comments($channel_id, $id = 0, $category = 0, $key = '')
    {
        if ($this->request->isPost()) {
            return redirect(url('', ['channel_id' => $channel_id, 'id' => $id, 'category' => $category, 'key' => base64url_encode($key)]));
        }
        $key = empty($key) ? "" : base64url_decode($key);
        $this->initChannel($channel_id);
        $model = Db::view('articleComment', '*')
            ->view('member', ['username', 'level_id', 'avatar'], 'member.id=articleComment.member_id', 'LEFT')
            ->view('article', ['title' => 'article_title', 'cate_id', 'cover'], 'article.id=articleComment.article_id', 'LEFT')
            ->view('category', ['name' => 'category_name', 'title' => 'category_title'], 'article.cate_id=category.id', 'LEFT');

        if ($id > 0) {
            $model->where('article_id', $id);
        }
        if ($category > 0) {
            $model->whereIn('article.cate_id', CategoryFacade::getSubCateIds($category));
        }
        if (!empty($key)) {
            $model->whereLike('article.title|category.title', "%$key%");
        }

        $lists = $model->order('articleComment.create_time desc')->paginate(10);

        $this->assign('lists', $lists);
        $this->assign('page', $lists->render());
        $this->assign('keyword', $key);
        $this->assign('article_id', $id);
        $this->assign('cate_id', $category);
        $this->assign("category", CategoryFacade::getCategories());

        return $this->fetch();
    }

    /**
     * 评论查看/回复
     * @param $id
     * @return mixed
     */
    public function commentview($channel_id, $id)
    {
        $model = Db::name('articleComment')->find($id);
        if (empty($model)) {
            $this->error('评论不存在');
        }
        $this->initChannel($channel_id);
        if ($this->request->isPost()) {
            $data = $this->request->post();
            unset($data['id']);
            $data['reply_id'] = $id;
            $data['group_id'] = empty($model['group_id']) ? $model['id'] : $model['group_id'];
            $data['status'] = 1;
            ArticleCommentModel::create($data);
            $this->success('回复成功');
        }
        $article = Db::name('article')->find($model['article_id']);
        $category = Db::name('category')->find($article['cate_id']);
        $member = Db::name('member')->find($model['member_id']);

        $this->assign('model', $model);
        $this->assign('replies', Db::name('articleComment')->where('group_id', $model['group_id'] ? $model['group_id'] : $id)->select());
        $this->assign('article', $article);
        $this->assign('category', $category);
        $this->assign('member', $member);
        return $this->fetch();
    }

    /**
     * 评论状态
     * @param $id
     * @param int $type
     */
    public function commentstatus($id, $type = 1)
    {
        $data['status'] = $type == 1 ? 1 : 2;

        $result = Db::name('articleComment')->where('id', 'in', idArr($id))->update($data);
        if ($result && $data['status'] === 1) {
            user_log($this->mid, 'auditcomment', 1, '审核评论 ' . $id, 'manager');
            $this->success("审核成功");
        } elseif ($result && $data['status'] === 2) {
            user_log($this->mid, 'hidecomment', 1, '隐藏评论 ' . $id, 'manager');
            $this->success("评论已隐藏");
        } else {
            $this->error("操作失败");
        }
    }

    /**
     * 删除评论
     * @param $id
     */
    public function commentdelete($id)
    {
        $model = Db::name('articleComment');
        $result = $model->where('id', 'in', idArr($id))->delete();
        if ($result) {
            user_log($this->mid, 'deletecomment', 1, '删除评论 ' . $id, 'manager');
            $this->success(lang('Delete success!'));
        } else {
            $this->error(lang('Delete failed!'));
        }
    }
}
